#include "config_addstyle.h"
#include "ui_config_addstyle.h"

config_addstyle::config_addstyle(QWidget *parent)
    : QWidget(parent), ui(new Ui::config_addstyle)
{
    ui->setupUi(this);
    // 初始化定时器
    // connect(&serialPortRefreshTimer, &QTimer::timeout, this, &config_addstyle::updateAvailableSerialPorts);
    // serialPortRefreshTimer.start(1000); // 每隔 1 秒触发一次
    // updateAvailableSerialPorts();
    // 为湿度限制输入框添加范围验证器 (0-99)
    QIntValidator *humLimitValidator = new QIntValidator(0, 99, this);
    ui->le_humLimit->setValidator(humLimitValidator);
    // 添加温度限制输入框的验证器
    QIntValidator *tempLimitValidator = new QIntValidator(0, 150, this);
    ui->le_tempLimit->setValidator(tempLimitValidator);
    ui->le_tempLimit2->setValidator(tempLimitValidator);
    QIntValidator *dbLimitValidator = new QIntValidator(0, 80, this);
    ui->le_dblimit1->setValidator(dbLimitValidator);
    ui->le_dblimit2->setValidator(dbLimitValidator);
    ui->label_2->setVisible(false);
    ui->uartComboBox->setVisible(false);
    ui->label->setVisible(false);
    ui->channalSpinBox->setVisible(false);
}

config_addstyle::~config_addstyle()
{
    delete ui;
}
void config_addstyle::updateAvailableSerialPorts()
{
    QString currentPort = ui->uartComboBox->currentText(); // 保存当前选中项
    // 清空之前的选项
    ui->uartComboBox->clear();

    // 获取所有可用串口信息
    const QList<QSerialPortInfo> serialPortInfos = QSerialPortInfo::availablePorts();

    if (serialPortInfos.isEmpty())
    {
        ui->uartComboBox->addItem("无可用串口");
        return;
    }

    // 遍历所有串口并添加到下拉框
    for (const QSerialPortInfo &info : serialPortInfos)
    {
        QString portName = info.systemLocation(); // 如 "COM1" 或 "/dev/ttyUSB0"
        ui->uartComboBox->addItem(portName);      // 也可以只添加 portName
        // qDebug() << "======used ports" << portName;
    }
    // 恢复之前选中的串口（如果仍然存在）
    int index = ui->uartComboBox->findText(currentPort);
    if (index != -1)
    {
        ui->uartComboBox->setCurrentIndex(index);
    }
}
/**
 * @brief config_addstyle::processJsonCommand 解析json
 * @param jsonStr
 */
bool config_addstyle::processJsonCommand(const QString &jsonStr, QString *err)
{
    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(jsonStr.toUtf8(), &error);

    if (error.error != QJsonParseError::NoError)
    {
        *err = "JSON analyse failed: " + error.errorString();
        return false;
    }

    QJsonObject root = doc.object();

    if (!root.contains("plugin_config"))
    {
        *err = "JSON format error: can not fine plugin_config seg";
        return false;
    }

    QJsonObject config = root["plugin_config"].toObject();
    channelId = config["channal"].toString();

    // qDebug() << "channal:" << channelId;
    // uartChannal = config["uartChannal"].toString();

    mTittle = config["tittle"].toString();
    ui->le_projectName->setText(mTittle);
    ui->le_tempLimit->setText(config["tempLimit_cd"].toString());
    ui->le_humLimit->setText(config["humLimit_hj"].toString());
    ui->le_tempLimit2->setText(config["tempLimit_hj"].toString());
    ui->le_dblimit1->setText(config["dbLImit_cs"].toString());
    ui->le_dblimit2->setText(config["dbLImit_zt"].toString());

    // bool containsPort = false;
    // for (int i = 0; i < ui->uartComboBox->count(); ++i)
    // {
    //     if (ui->uartComboBox->itemText(i) == uartChannal)
    //     {
    //         containsPort = true;
    //         break;
    //     }
    // }
    // // 如果存在对应内容，则设置为当前选中项
    // if (containsPort)
    // {
    ui->uartComboBox->setCurrentText(uartChannal);
    // }
    // else
    // {
    //     qDebug() << "未找到对应的串口：" << uartChannal;
    // }
    QJsonArray blocks = config["blocks"].toArray();
    m_configInfoList.clear();

    for (const QJsonValue &blockVal : blocks)
    {
        QJsonObject blockObj = blockVal.toObject();
        QString blockId = blockObj["block_id"].toString();
        QString blockName = blockObj["block_name"].toString();
        QJsonArray params = blockObj["parameters"].toArray();

        QMap<QString, ConfigInfo> paramMap;
        for (const QJsonValue &paramVal : params)
        {
            QJsonObject paramObj = paramVal.toObject();
            ConfigInfo info(paramObj); // 使用构造函数初始化
            paramMap.insert(info.identifier, info);
        }

        m_configInfoList.append(qMakePair(blockName, paramMap));
    }
    updateLayout();
    mLevel = config["permission"].toString();
    // qDebug() << "permission:" << mLevel;
    if (mLevel == "1")
    {
        ui->pushButton_add->setEnabled(true);
        ui->pushButton_change->setEnabled(true);
        ui->pushButton_delete->setEnabled(true);
        ui->normalWidget->setEnabled(true);
        // 遍历tabWidget_info里面的tab信息，取出来变成config_infoSet
        for (int i = 0; i < ui->tabWidget_info->count(); ++i)
        {
            QWidget *tabContent = ui->tabWidget_info->widget(i);
            config_infoSet *configSet = dynamic_cast<config_infoSet *>(tabContent);
            if (configSet)
            {
                configSet->setOperateEnable(true);
            }
        }
    }
    else
    {
        ui->pushButton_add->setEnabled(false);
        ui->pushButton_change->setEnabled(false);
        ui->pushButton_delete->setEnabled(false);
        ui->normalWidget->setEnabled(false);
        for (int i = 0; i < ui->tabWidget_info->count(); ++i)
        {
            QWidget *tabContent = ui->tabWidget_info->widget(i);
            config_infoSet *configSet = dynamic_cast<config_infoSet *>(tabContent);
            if (configSet)
            {
                configSet->setOperateEnable(false);
            }
        }
    }
    return true;
}

/**
 * @brief config_addstyle::updateLayout 根据m_configInfoList重新刷新config页面布局
 */
void config_addstyle::updateLayout()
{
    ui->channalSpinBox->setValue(channelId.toInt());
    // 清除所有现有标签页
    while (ui->tabWidget_info->count() > 0)
    {
        QWidget *tab = ui->tabWidget_info->widget(0);
        ui->tabWidget_info->removeTab(0);
        delete tab;
    }

    // 重建新的标签页
    for (const auto &pair : m_configInfoList)
    {
        QString blockName = pair.first;
        QMap<QString, ConfigInfo> params = pair.second;

        config_infoSet *newTab = new config_infoSet(nullptr, blockName);
        newTab->setParameters(params); // 需要config_infoSet实现该接口
        ui->tabWidget_info->addTab(newTab, blockName);
    }
}

/**
 * @brief config_addstyle::on_pushButton_add_clicked 新增按钮按下
 */
void config_addstyle::on_pushButton_add_clicked()
{
    // 创建自定义对话框
    QDialog dialog(this);
    dialog.setWindowTitle("新增机柜");
    QFormLayout form(&dialog);

    // 输入框
    CustomLineEdit lineEdit;
    lineEdit.setPlaceholderText("如：A柜");
    form.addRow("请输入柜名：", &lineEdit);

    // 按钮
    QDialogButtonBox btnBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    form.addRow(&btnBox);

    // 连接按钮信号
    connect(&btnBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
    connect(&btnBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
    btnBox.button(QDialogButtonBox::Ok)->setText("是");
    btnBox.button(QDialogButtonBox::Cancel)->setText("否");
    // 设置模态级别（关键！）
    dialog.setWindowModality(Qt::WindowModal);

    // 设置焦点（确保虚拟键盘能弹出）
    lineEdit.setFocus();

    // 显示对话框并获取结果
    if (dialog.exec() == QDialog::Accepted)
    {
        QString cabinetName = lineEdit.text().trimmed();

        if (!cabinetName.isEmpty())
        {
            // 检查重复名称
            bool nameExists = false;
            for (int i = 0; i < ui->tabWidget_info->count(); ++i)
            {
                if (ui->tabWidget_info->tabText(i) == cabinetName)
                {
                    nameExists = true;
                    break;
                }
            }

            if (nameExists)
            {
                QMessageBox::warning(this, "名称冲突", "已存在同名机柜，请使用其他名称");
                return;
            }

            // 添加新标签页
            config_infoSet *newTab = new config_infoSet(nullptr, cabinetName);
            // 获取当前选中的标签页索引
            int currentIndex = ui->tabWidget_info->currentIndex();

            // 如果当前有选中的标签页，则插入到其后；否则插入到最后
            if (currentIndex >= 0)
            {
                // 插入到当前选中标签页的后面
                ui->tabWidget_info->insertTab(currentIndex + 1, newTab, cabinetName);
                // 将当前选中的标签页切换到新创建的页面
                ui->tabWidget_info->setCurrentIndex(currentIndex + 1);
            }
            else
            {
                // 如果没有选中的标签页，插入到最后
                ui->tabWidget_info->addTab(newTab, cabinetName);
                ui->tabWidget_info->setCurrentIndex(ui->tabWidget_info->count() - 1);
            }

            // 同时更新内部数据结构
            QMap<QString, ConfigInfo> emptyParams;
            m_configInfoList.insert(currentIndex + 1, qMakePair(cabinetName, emptyParams));
        }
    }
}

/**
 * @brief config_addstyle::on_pushButton_delete_clicked 删除选中的页面
 */
void config_addstyle::on_pushButton_delete_clicked()
{
    int currentIndex = ui->tabWidget_info->currentIndex();
    if (currentIndex != -1)
    {
        QMessageBox msgBox(this);
        msgBox.setWindowTitle("确认删除");
        msgBox.setText("确定要删除当前页吗？");
        msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
        msgBox.setButtonText(QMessageBox::Yes, "是");
        msgBox.setButtonText(QMessageBox::No, "否");

        if (msgBox.exec() == QMessageBox::Yes)
        {
            QWidget *tab = ui->tabWidget_info->widget(currentIndex);
            ui->tabWidget_info->removeTab(currentIndex);
            delete tab;

            // 同时更新内部数据结构
            if (currentIndex < m_configInfoList.size())
            {
                m_configInfoList.removeAt(currentIndex);
            }
        }
    }
}

/**
 * @brief config_addstyle::on_pushButton_save_clicked 存储当前所有信息
 */
void config_addstyle::on_pushButton_save_clicked()
{
    // 清空list
    m_configInfoList.clear();
    // 遍历所有标签页，重新生成list
    for (int i = 0; i < ui->tabWidget_info->count(); ++i)
    {
        QWidget *tabContent = ui->tabWidget_info->widget(i);
        config_infoSet *configSet = dynamic_cast<config_infoSet *>(tabContent);
        if (configSet)
        {
            // 获取当前标签名称作为key
            QString tabName = ui->tabWidget_info->tabText(i);
            // 假设getConfigInfo()返回配置参数的QVector/QMap等容器
            m_configInfoList.append(qMakePair(tabName, configSet->getConfigInfo()));
        }
    }

    // 根据m_configInfoList刷新json文件
    QJsonObject pluginConfigObj;
    int channalIdInt = ui->channalSpinBox->value();
    pluginConfigObj["channal"] = QString::number(channalIdInt);
    pluginConfigObj["uartChannal"] = uartChannal;
    pluginConfigObj["permission"] = mLevel;
    pluginConfigObj["tempLimit_cd"] = ui->le_tempLimit->text();
    pluginConfigObj["tempLimit_hj"] = ui->le_tempLimit2->text();
    pluginConfigObj["humLimit_hj"] = ui->le_humLimit->text();
    pluginConfigObj["dbLImit_cs"] = ui->le_dblimit1->text();
    pluginConfigObj["dbLImit_zt"] = ui->le_dblimit2->text();
    pluginConfigObj["tittle"] = ui->le_projectName->text();
    QJsonArray blocks;

    for (const auto &pair : m_configInfoList)
    {
        QString blockName = pair.first;
        const QMap<QString, ConfigInfo> &params = pair.second;

        QJsonObject blockObj;
        blockObj["block_name"] = blockName;

        QJsonArray paramsArray;
        int identifierCounter = 1; // 每个block内identifier从1开始

        // 定义allLocations顺序
        QStringList allLocations;
        allLocations << "母线A" << "母线B" << "母线C"
                     << "上触头A" << "上触头B" << "上触头C"
                     << "下触头A" << "下触头B" << "下触头C"
                     << "电缆A" << "电缆B" << "电缆C"
                     << "柜内温度" << "柜内湿度"
                     << "超声波" << "暂态地电压";

        // 按allLocations顺序对参数进行排序
        QList<ConfigInfo> sortedParams;

        // 首先按allLocations顺序添加参数
        for (const QString &location : allLocations)
        {
            // 查找params中是否有这个位置
            for (auto paramIt = params.begin(); paramIt != params.end(); ++paramIt)
            {
                if (paramIt.value().position == location)
                {
                    sortedParams.append(paramIt.value());
                    break;
                }
            }
        }

        // 然后添加不在allLocations中的参数（如果有的话）
        for (auto paramIt = params.begin(); paramIt != params.end(); ++paramIt)
        {
            if (!allLocations.contains(paramIt.value().position))
            {
                sortedParams.append(paramIt.value());
            }
        }

        // 遍历排序后的参数项
        for (const ConfigInfo &info : sortedParams)
        {
            QJsonObject paramObj;

            // 根据示例数据生成固定字段
            paramObj["data"] = "--";
            paramObj["modbusAddr"] = QString::number(info.id);
            paramObj["identifier"] = QString::number(identifierCounter++);
            paramObj["position"] = info.position;
            paramObj["type"] = info.dataType;

            paramsArray.append(paramObj);
        }
        blockObj["parameters"] = paramsArray;
        blocks.append(blockObj);
    }
    pluginConfigObj["blocks"] = blocks;
    // 构建根对象
    QJsonObject root;
    root["plugin_config"] = pluginConfigObj;
    // 生成JSON文档
    QJsonDocument doc(root);
    QFile file("config/config.json");
    if (file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        file.write(doc.toJson());
        file.close();
    }
    // QTimer::singleShot(1000, this, [=]()
    //                    { emit signalToForward("config.json updated"); });
    // 添加提示框询问是否重启以生效配置
    QMessageBox msgBox(this);
    msgBox.setWindowTitle("配置已保存");
    msgBox.setText("配置已保存成功，是否需要重启以使配置生效？");
    msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
    msgBox.setButtonText(QMessageBox::Yes, "是");
    msgBox.setButtonText(QMessageBox::No, "否");

    if (msgBox.exec() == QMessageBox::Yes)
    {
        // 发送重启信号或执行重启操作
        emit signalToForward("config.json updated");
    }
}
struct Parameter
{
    QString modbusAddr;
    QString position;
    QString type;
};
void config_addstyle::parseExternalConfigToMap(const QString &filePath)
{
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly))
    {
        qDebug() << "无法打开文件：" << filePath;
        return;
    }

    QByteArray data = file.readAll();
    file.close();

    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(data, &error);
    if (error.error != QJsonParseError::NoError)
    {
        qDebug() << "JSON 解析失败：" << error.errorString();
        return;
    }

    QJsonObject root = doc.object();

    // 检查是否为完整配置格式（包含 plugin_config）
    if (root.contains("plugin_config"))
    {
        QJsonObject config = root["plugin_config"].toObject();

        // 读取全局配置
        channelId = config["channal"].toString();
        mTittle = config["tittle"].toString();

        // 更新UI控件
        ui->le_projectName->setText(mTittle);
        ui->le_tempLimit->setText(config["tempLimit_cd"].toString());
        ui->le_humLimit->setText(config["humLimit_hj"].toString());
        ui->le_tempLimit2->setText(config["tempLimit_hj"].toString());
        ui->le_dblimit1->setText(config["dbLImit_cs"].toString());
        ui->le_dblimit2->setText(config["dbLImit_zt"].toString());

        // uartChannal = config["uartChannal"].toString();
        // 查找并设置串口号
        // bool containsPort = false;
        // for (int i = 0; i < ui->uartComboBox->count(); ++i)
        // {
        //     if (ui->uartComboBox->itemText(i) == uartChannal)
        //     {
        //         containsPort = true;
        //         break;
        //     }
        // }
        // if (containsPort)
        // {
        // ui->uartComboBox->setCurrentText(uartChannal);
        // }
        // else
        // {
        //     qDebug() << "未找到对应的串口：" << uartChannal;
        // }

        // 设置通道号
        ui->channalSpinBox->setValue(channelId.toInt());

        // 解析blocks部分
        QJsonArray blocks = config["blocks"].toArray();
        m_configInfoList.clear();

        for (const QJsonValue &blockVal : blocks)
        {
            QJsonObject blockObj = blockVal.toObject();
            QString blockName = blockObj["block_name"].toString();
            QJsonArray params = blockObj["parameters"].toArray();

            QMap<QString, ConfigInfo> paramMap;
            int identifierCounter = 1;

            for (const QJsonValue &paramVal : params)
            {
                QJsonObject paramObj = paramVal.toObject();
                ConfigInfo info;
                info.id = paramObj["modbusAddr"].toString().toInt();
                info.position = paramObj["position"].toString();
                info.dataType = paramObj["type"].toString();
                info.identifier = QString::number(identifierCounter++);
                info.data = "--";

                paramMap.insert(info.identifier, info);
            }
            m_configInfoList.append(qMakePair(blockName, paramMap));
        }
    }
    // 兼容旧格式（只有机柜数据）
    else
    {
        m_configInfoList.clear();

        for (auto it = root.begin(); it != root.end(); ++it)
        {
            QString blockName = it.key();
            QJsonObject blockObj = it.value().toObject();

            QJsonArray parametersArray = blockObj["parameters"].toArray();
            QMap<QString, ConfigInfo> paramMap;
            int identifierCounter = 1;

            for (const QJsonValue &paramValue : parametersArray)
            {
                QJsonObject paramObj = paramValue.toObject();
                ConfigInfo info;
                info.id = paramObj["modbusAddr"].toString().toInt();
                info.position = paramObj["position"].toString();
                info.dataType = paramObj["type"].toString();
                info.identifier = QString::number(identifierCounter++);
                info.data = "--";
                paramMap.insert(info.identifier, info);
            }
            m_configInfoList.append(qMakePair(blockName, paramMap));
        }
    }

    updateLayout();
    qDebug() << "成功解析并更新配置";
}
void config_addstyle::on_pb_inport_clicked()
{
    QFileDialog fileDialog(this);
    fileDialog.setWindowModality(Qt::WindowModal); // 添加这一行
    fileDialog.setWindowTitle(tr("选择配置文件"));
    fileDialog.setFileMode(QFileDialog::ExistingFile);
    fileDialog.setNameFilter(tr("JSON 文件 (*.json);;所有文件 (*)"));

    QString filePath;
    if (fileDialog.exec() == QDialog::Accepted)
    {
        filePath = fileDialog.selectedFiles().first();
        parseExternalConfigToMap(filePath);
        updateLayout();
    }
    else
    {
        qDebug() << "未选择文件";
    }
}

void config_addstyle::on_pb_export_clicked()
{
    QFileDialog fileDialog(this);
    fileDialog.setWindowModality(Qt::WindowModal); // 设置模态级别
    fileDialog.setWindowTitle(tr("保存配置文件"));
    fileDialog.setAcceptMode(QFileDialog::AcceptSave);
    fileDialog.setNameFilter(tr("JSON 文件 (*.json);;所有文件 (*)"));
    fileDialog.setDefaultSuffix("json");

    QString filePath;
    if (fileDialog.exec() == QDialog::Accepted)
    {
        filePath = fileDialog.selectedFiles().first();

        // 确保文件具有.json扩展名
        if (!filePath.endsWith(".json", Qt::CaseInsensitive))
        {
            filePath += ".json";
        }

        // 构建完整的配置JSON结构
        QJsonObject pluginConfigObj;
        pluginConfigObj["channal"] = QString::number(ui->channalSpinBox->value());
        pluginConfigObj["uartChannal"] = uartChannal;
        pluginConfigObj["permission"] = mLevel;
        pluginConfigObj["tempLimit_cd"] = ui->le_tempLimit->text();
        pluginConfigObj["tempLimit_hj"] = ui->le_tempLimit2->text();
        pluginConfigObj["humLimit_hj"] = ui->le_humLimit->text();
        pluginConfigObj["dbLImit_cs"] = ui->le_dblimit1->text();
        pluginConfigObj["dbLImit_zt"] = ui->le_dblimit2->text();
        pluginConfigObj["tittle"] = ui->le_projectName->text();

        QJsonArray blocks;
        for (const auto &pair : m_configInfoList)
        {
            QString blockName = pair.first;
            const QMap<QString, ConfigInfo> &params = pair.second;

            QJsonObject blockObj;
            blockObj["block_name"] = blockName;

            QJsonArray paramsArray;
            for (auto paramIt = params.begin(); paramIt != params.end(); ++paramIt)
            {
                const ConfigInfo &info = paramIt.value();
                QJsonObject paramObj;
                paramObj["modbusAddr"] = QString::number(info.id);
                paramObj["position"] = info.position;
                paramObj["type"] = info.dataType;
                paramsArray.append(paramObj);
            }
            blockObj["parameters"] = paramsArray;
            blocks.append(blockObj);
        }
        pluginConfigObj["blocks"] = blocks;

        // 构建根对象
        QJsonObject root;
        root["plugin_config"] = pluginConfigObj;

        // 保存 JSON 到文件
        QJsonDocument doc(root);
        QFile file(filePath);

        if (file.open(QIODevice::WriteOnly | QIODevice::Text))
        {
            file.write(doc.toJson());
            file.close();
            qDebug() << "配置文件已成功保存到：" << filePath;
            QMessageBox msgBoxInfo(this);
            msgBoxInfo.setWindowTitle(tr("导出成功"));
            msgBoxInfo.setText(tr("配置文件已成功导出到：%1").arg(filePath));
            msgBoxInfo.setStandardButtons(QMessageBox::Ok);
            msgBoxInfo.setButtonText(QMessageBox::Ok, "确定");
            msgBoxInfo.exec();
        }
        else
        {
            qDebug() << "无法写入文件：" << filePath;
            QMessageBox msgBoxError(this);
            msgBoxError.setWindowTitle(tr("错误"));
            msgBoxError.setText(tr("无法写入文件：%1").arg(filePath));
            msgBoxError.setStandardButtons(QMessageBox::Ok);
            msgBoxError.setButtonText(QMessageBox::Ok, "确定");
            msgBoxError.exec();
        }
    }
    else
    {
        qDebug() << "未选择保存路径";
    }
}
void config_addstyle::on_le_tempLimit_textChanged(const QString &arg1)
{
    if (!arg1.isEmpty())
    {
        bool ok;
        int value = arg1.toInt(&ok);
        if (ok)
        {
            if (value > 150)
            {
                // 限制最大值为150
                ui->le_tempLimit->setText("150");
                // 将光标移到末尾
                ui->le_tempLimit->setCursorPosition(QString("150").length());
            }
            else if (value < 0)
            {
                // 限制最小值为0
                ui->le_tempLimit->setText("0");
                ui->le_tempLimit->setCursorPosition(QString("0").length());
            }
        }
    }
}

void config_addstyle::on_le_humLimit_textChanged(const QString &arg1)
{
    if (!arg1.isEmpty())
    {
        bool ok;
        int value = arg1.toInt(&ok);
        if (ok)
        {
            if (value > 99)
            {
                // 限制最大值为99
                ui->le_humLimit->setText("99");
                // 将光标移到末尾
                ui->le_humLimit->setCursorPosition(QString("99").length());
            }
            else if (value < 0)
            {
                // 限制最小值为0
                ui->le_humLimit->setText("0");
                ui->le_humLimit->setCursorPosition(QString("0").length());
            }
        }
    }
}

void config_addstyle::on_le_projectName_textChanged(const QString &arg1)
{
    mTittle = arg1;
}

void config_addstyle::on_pushButton_change_clicked()
{
    int currentIndex = ui->tabWidget_info->currentIndex();
    if (currentIndex == -1)
    {
        QMessageBox::warning(this, "警告", "没有选中的机柜");
        return;
    }

    QString currentTabText = ui->tabWidget_info->tabText(currentIndex);

    // 创建自定义对话框
    QDialog dialog(this);
    dialog.setWindowTitle("修改机柜名称");
    QFormLayout form(&dialog);

    // 输入框
    CustomLineEdit lineEdit;
    lineEdit.setText(currentTabText);
    lineEdit.selectAll(); // 选中所有文本方便修改
    form.addRow("请输入新的柜名：", &lineEdit);

    // 按钮
    QDialogButtonBox btnBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    form.addRow(&btnBox);

    // 连接按钮信号
    connect(&btnBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
    connect(&btnBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
    btnBox.button(QDialogButtonBox::Ok)->setText("确定");
    btnBox.button(QDialogButtonBox::Cancel)->setText("取消");

    // 设置模态级别
    dialog.setWindowModality(Qt::WindowModal);
    // 设置焦点
    lineEdit.setFocus();

    // 显示对话框并获取结果
    if (dialog.exec() == QDialog::Accepted)
    {
        QString newName = lineEdit.text().trimmed();

        if (newName.isEmpty())
        {
            QMessageBox::warning(this, "输入错误", "机柜名称不能为空");
            return;
        }

        // 检查是否有重名（排除自己）
        bool nameExists = false;
        for (int i = 0; i < ui->tabWidget_info->count(); ++i)
        {
            if (i != currentIndex && ui->tabWidget_info->tabText(i) == newName)
            {
                nameExists = true;
                break;
            }
        }

        if (nameExists)
        {
            QMessageBox::warning(this, "名称冲突", "已存在同名机柜，请使用其他名称");
            return;
        }

        // 修改标签页标题
        ui->tabWidget_info->setTabText(currentIndex, newName);

        // 更新对应的config_infoSet的blockName
        QWidget *tabContent = ui->tabWidget_info->widget(currentIndex);
        config_infoSet *configSet = dynamic_cast<config_infoSet *>(tabContent);
        if (configSet)
        {
            configSet->setBlockName(newName);
        }

        // 更新内部数据结构
        if (currentIndex < m_configInfoList.size())
        {
            m_configInfoList[currentIndex].first = newName;
        }
    }
}